using UnityEngine;
using System.Collections;

public class Cannon : MonoBehaviour {
	
	public GameObject shoot;
	public float cadencia = 1;
	public float accuracyX = 5;
	public float accuracyY = 5;
	bool targetLocked = false;
	int counterFire = 0;
	bool berseker = false;
	float startTimer = 0;
	float accX = 0;
	float accY = 0;

	// Use this for initialization
	void Start () {
		accX = Random.Range(-accuracyX, accuracyX);	
		accY = Random.Range(-accuracyY, accuracyY);	
	}
	
	// Update is called once per frame
	void Update () {
		BersekerMode();
	}
	 
	void OnTriggerEnter(Collider other)
	{
		if (other.gameObject.tag == "xwing")
		{
			berseker = true;
			Debug.Log("TESTE");
			
		}
		
	}
	
	/// <summary>
	/// Bersekers the mode.
	/// </summary>
	void BersekerMode()
	{
		if (berseker)
		{
			TrackEnemy();
			Fire ();
			
		}
	}
	
	/// <summary>
	/// Rapid Fire
	/// </summary>
	void Fire()
	{
		if (startTimer == 0)
				startTimer = Time.time;
				
			if ((Time.time - startTimer) > cadencia)
			{
				if (targetLocked)
				{
					Instantiate(shoot, GameObject.FindWithTag("turret1").transform.position, GameObject.FindWithTag("blaster1").transform.rotation);	
					counterFire++;
					startTimer = 0;
				}
			}
	}
	
	void TrackEnemy()
	{
		Transform xwing = GameObject.FindWithTag("xwing").transform;
		
		Transform cannon = GameObject.FindWithTag("turret1").transform;
		
		//float deltaY = Vector3.Angle(cannon.position - xwing.position, cannon.forward);
		
		//deltaY = Vector3.Angle(Vector3.Normalize(xwing.position), Vector3.Normalize(cannon.position));
		
		//float delta = Mathf.SmoothDampAngle(cannon.eulerAngles.y, xwing.eulerAngles.y, ref yVelocity, 0.3f);
		
		//Debug.Log(deltaY);
		
		//if ( deltaY > accuracy )
		//{
			//float linearDelta = Mathf.LerpAngle(0, deltaY, Time.deltaTime);
			//cannon.Rotate(0,linearDelta, 0);	
		RotateTowardsYOnly(xwing.position);
		
		RotateTowardsXOnly(xwing.position);
			//targetLocked  = false;
		//}
		//else
		targetLocked  = true;
		//targetRay = new Ray(GameObject.FindWithTag("cannon1").transform.position, GameObject.FindWithTag("xwing").transform.position);

	    //point = targetRay.GetPoint(0);
	
	    //point = Vector3.Slerp(GameObject.FindWithTag("cannon1").transform.position, point, Time.deltaTime * 10f);
	}
	
	public void RotateTowardsYOnly(Vector3 targetPos)
	{
    	targetPos.y = GameObject.FindWithTag("turret1").transform.position.y;
		targetPos.x += accX;
		//Vector3 smoothTarget = Vector3.Lerp(targetPos - new Vector3(0,0,-10),targetPos,0.001f);
    	GameObject.FindWithTag("turret1").transform.LookAt(targetPos);
	}
	
	public void RotateTowardsXOnly(Vector3 targetPos)
	{
    	//targetPos.x = GameObject.FindWithTag("blaster1").transform.position.x;
		targetPos.y += accY;
		//Vector3 smoothTarget = Vector3.Lerp(targetPos - new Vector3(0,0,-10),targetPos,0.001f);
    	GameObject.FindWithTag("blaster1").transform.LookAt(targetPos);
	}
}
